'use client';

import { useEffect, useState, useRef } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import Image from 'next/image';
import NoTabBarLayout from '../../../components/layout/NoTabBarLayout';
import { useSocket, Message, User } from '../../../context/SocketContext';
import styles from './page.module.css';

export default function ChatPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const chatId = searchParams.get('id');
  const chatType = searchParams.get('type') as 'private' | 'group';
  const chatName = searchParams.get('name');
  const chatAvatar = searchParams.get('avatar');
  
  const {
    currentUser,
    messages,
    sendPrivateMessage,
    sendGroupMessage,
    loadPrivateChatHistory,
    loadGroupChatHistory,
    getGroupMembers,
    groupMembers,
    friends
  } = useSocket();
  
  const [inputMessage, setInputMessage] = useState('');
  const [showInfo, setShowInfo] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  
  // 加载聊天历史
  useEffect(() => {
    if (chatId && chatType) {
      if (chatType === 'private') {
        loadPrivateChatHistory(chatId);
      } else if (chatType === 'group') {
        loadGroupChatHistory(chatId);
        getGroupMembers(chatId);
      }
    }
  }, [chatId, chatType, loadPrivateChatHistory, loadGroupChatHistory, getGroupMembers]);
  
  // 滚动到最新消息
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);
  
  // 处理发送消息
  const handleSendMessage = () => {
    if (!inputMessage.trim() || !chatId || !chatType) return;
    
    if (chatType === 'private') {
      sendPrivateMessage(chatId, inputMessage);
    } else if (chatType === 'group') {
      sendGroupMessage(chatId, inputMessage);
    }
    
    setInputMessage('');
  };
  
  // 处理按键事件
  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };
  
  // 获取用户信息
  const getUserInfo = (userId: string): User | undefined => {
    if (currentUser?.id === userId) return currentUser;
    return friends.find(friend => friend.id === userId);
  };
  
  // 格式化时间
  const formatTime = (timestamp: number) => {
    const date = new Date(timestamp);
    return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
  };
  
  // 处理返回
  const handleBack = () => {
    router.push('/message');
  };
  
  // 处理查看信息
  const handleViewInfo = () => {
    setShowInfo(true);
  };
  
  // 处理关闭信息
  const handleCloseInfo = () => {
    setShowInfo(false);
  };
  
  if (!chatId || !chatType || !chatName) {
    return <div>无效的聊天</div>;
  }
  
  return (
    <NoTabBarLayout>
      <div className={styles.chatPage}>
        {/* 聊天头部 */}
        <div className={styles.chatHeader}>
          <div className={styles.backButton} onClick={handleBack}>
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M20 11H7.83L13.42 5.41L12 4L4 12L12 20L13.41 18.59L7.83 13H20V11Z" fill="#333"/>
            </svg>
          </div>
          <div className={styles.chatInfo} onClick={handleViewInfo}>
            <div className={styles.chatName}>{chatName}</div>
            <div className={styles.chatStatus}>
              {chatType === 'private' ? '在线' : `${groupMembers.length}人`}
            </div>
          </div>
          <div className={styles.moreButton}>
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M12 8C13.1 8 14 7.1 14 6C14 4.9 13.1 4 12 4C10.9 4 10 4.9 10 6C10 7.1 10.9 8 12 8ZM12 10C10.9 10 10 10.9 10 12C10 13.1 10.9 14 12 14C13.1 14 14 13.1 14 12C14 10.9 13.1 10 12 10ZM12 16C10.9 16 10 16.9 10 18C10 19.1 10.9 20 12 20C13.1 20 14 19.1 14 18C14 16.9 13.1 16 12 16Z" fill="#333"/>
            </svg>
          </div>
        </div>
        
        {/* 聊天内容 */}
        <div className={styles.chatContent}>
          {messages.map((message: Message) => {
            const isCurrentUser = message.sender === currentUser?.id;
            const sender = getUserInfo(message.sender);
            
            return (
              <div 
                key={message.id} 
                className={`${styles.messageItem} ${isCurrentUser ? styles.messageRight : styles.messageLeft}`}
              >
                {!isCurrentUser && (
                  <div className={styles.messageSenderAvatar}>
                    <Image 
                      src={sender?.avatar || '/avatars/avatar1.svg'} 
                      alt={sender?.username || '用户'} 
                      width={40} 
                      height={40} 
                      className={styles.avatar}
                    />
                  </div>
                )}
                <div className={styles.messageContent}>
                  {chatType === 'group' && !isCurrentUser && (
                    <div className={styles.messageSenderName}>
                      {sender?.username || '用户'}
                    </div>
                  )}
                  <div className={styles.messageBubble}>
                    {message.content}
                  </div>
                  <div className={styles.messageTime}>
                    {formatTime(message.timestamp)}
                  </div>
                </div>
                {isCurrentUser && (
                  <div className={styles.messageSenderAvatar}>
                    <Image 
                      src={currentUser.avatar} 
                      alt={currentUser.username} 
                      width={40} 
                      height={40} 
                      className={styles.avatar}
                    />
                  </div>
                )}
              </div>
            );
          })}
          <div ref={messagesEndRef} />
        </div>
        
        {/* 输入框 */}
        <div className={styles.inputContainer}>
          <div className={styles.inputActions}>
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M12 18.5C15.5899 18.5 18.5 15.5899 18.5 12C18.5 8.41015 15.5899 5.5 12 5.5C8.41015 5.5 5.5 8.41015 5.5 12C5.5 15.5899 8.41015 18.5 12 18.5Z" stroke="#999" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
              <path d="M12 12.5C12.2761 12.5 12.5 12.2761 12.5 12C12.5 11.7239 12.2761 11.5 12 11.5C11.7239 11.5 11.5 11.7239 11.5 12C11.5 12.2761 11.7239 12.5 12 12.5Z" stroke="#999" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
              <path d="M16 12.5C16.2761 12.5 16.5 12.2761 16.5 12C16.5 11.7239 16.2761 11.5 16 11.5C15.7239 11.5 15.5 11.7239 15.5 12C15.5 12.2761 15.7239 12.5 16 12.5Z" stroke="#999" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
              <path d="M8 12.5C8.27614 12.5 8.5 12.2761 8.5 12C8.5 11.7239 8.27614 11.5 8 11.5C7.72386 11.5 7.5 11.7239 7.5 12C7.5 12.2761 7.72386 12.5 8 12.5Z" stroke="#999" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </div>
          <div className={styles.inputBox}>
            <textarea 
              className={styles.inputField}
              placeholder="发送消息..."
              value={inputMessage}
              onChange={(e) => setInputMessage(e.target.value)}
              onKeyDown={handleKeyDown}
            />
          </div>
          <div 
            className={`${styles.sendButton} ${inputMessage.trim() ? styles.sendButtonActive : ''}`}
            onClick={handleSendMessage}
          >
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M2.01 21L23 12L2.01 3L2 10L17 12L2 14L2.01 21Z" fill={inputMessage.trim() ? '#2b7efb' : '#999'}/>
            </svg>
          </div>
        </div>
        
        {/* 用户/群组信息侧边栏 */}
        {showInfo && (
          <div className={styles.infoSidebar}>
            <div className={styles.infoHeader}>
              <div className={styles.closeButton} onClick={handleCloseInfo}>
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M19 6.41L17.59 5L12 10.59L6.41 5L5 6.41L10.59 12L5 17.59L6.41 19L12 13.41L17.59 19L19 17.59L13.41 12L19 6.41Z" fill="#333"/>
                </svg>
              </div>
              <div className={styles.infoTitle}>
                {chatType === 'private' ? '联系人信息' : '群组信息'}
              </div>
            </div>
            <div className={styles.infoContent}>
              <div className={styles.infoAvatar}>
                <Image 
                  src={chatAvatar || '/avatars/avatar1.svg'} 
                  alt={chatName} 
                  width={80} 
                  height={80} 
                  className={styles.avatarLarge}
                />
              </div>
              <div className={styles.infoName}>{chatName}</div>
              
              {chatType === 'group' && (
                <div className={styles.membersList}>
                  <div className={styles.membersTitle}>群组成员 ({groupMembers.length})</div>
                  {groupMembers.map((member) => (
                    <div key={member.id} className={styles.memberItem}>
                      <div className={styles.memberAvatar}>
                        <Image 
                          src={member.avatar} 
                          alt={member.username} 
                          width={40} 
                          height={40} 
                          className={styles.avatar}
                        />
                      </div>
                      <div className={styles.memberInfo}>
                        <div className={styles.memberName}>{member.username}</div>
                        <div className={styles.memberStatus}>
                          {member.online ? '在线' : '离线'}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>
        )}
      </div>
    </NoTabBarLayout>
  );
}